<?php

namespace app\admin\controller\facrm\business;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 *商机管理
 */
class Index extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['product'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Business');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'business')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');
        if ($this->request->isAjax()) {

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_w = [];
            $filter_w['owner_user_id'] = $this->auth->id;
            if (isset($filter['scene_id'])) {
                if (!isset($scene_list[$filter['scene_id']])) {
                    $this->error(__("您没有权限"));
                }
                switch ($filter['scene_id']) {
                    case 7:
                        //全部客户 超级管理员不做限制
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                        if ($this->childrenAdminIds)//修复没有下属的时候获得公共客户
                            $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    case 8:
                        //我的客户
                        $filter_w['owner_user_id'] = $this->auth->id;
                        break;
                    case 9:
                        //下属客户

                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                        if ($this->childrenAdminIds)//修复没有下属的时候获得公共客户
                            $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    default://其它的还做TODO
                        $filter_w['owner_user_id'] = $this->auth->id;

                }

                unset($filter['scene_id']);
                $this->request->get(['filter' => json_encode($filter)]);
            }

            $customer_id = $this->request->param("customer_id");
            if ($customer_id) {
                $filter_w['customer_id'] = $customer_id;
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'ownerUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {

            $this->assignconfig("is_end_list", $this->model->getIsEndList());
            $this->view->assign("scene_list", $scene_list);
        }

        /**
         * 自定义字段
         */
        $fields = \app\admin\model\facrm\Fields::getCustomFieldsTable('business', [], 'isfilter=1 or islist=1');
        if ($fields) {
            $this->assignconfig('fields', json_encode($fields));
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));

            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            if (!in_array($row_c['owner_user_id'], $this->childrenAdminIds)) {
                $this->error(__('You have no permission'));
            }
            $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : 0;
            $params['deal_time'] = $params['deal_time'] ? strtotime($params['deal_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $row_c['owner_user_id'],
                'type_id' => '1',
                'status' => 1,
            ]);

            $params = $this->preExcludeFields($params);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $this->model->validateFailException(true)->validate($validate);
                }
                $result = $this->model->allowField(true)->save($params);
                //添加商机产品
                $product_data = ($this->request->post("product/a"));
                $business_id = $this->model->id;

                foreach ($product_data as &$row) {
                    $row['business_id'] = $business_id;
                }
                $this->model->product()->saveAll($product_data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 修改
     * @param null $ids
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkBusinessAuth($row, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        if (!$auth->checkCustomerAuth($row->customer, $this->auth)) {
            $this->error(__('您没有权限:客户权限'));
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['next_time'] = $params['next_time'] ? strtotime($params['next_time']) : 0;
                $params['deal_time'] = $params['deal_time'] ? strtotime($params['deal_time']) : 0;
                $result = false;
                Db::startTrans();

                try {
                    if ($row->is_end != 0) exception(__("不能修改的状态"));
                    if ($params['is_end'] == 1) exception(__("不能手动改成成交状态，请添加合同！"));
                    $business_id = $row->id;
                    $result = $row->allowField(true)->save($params);
                    if ($result) {
                        //更新产品,先全部删除再添加
                        $productModel = model('\app\admin\model\facrm\business\Product');
                        $this->model->product()->where('business_id', $business_id)->delete();
                        $product_data = ($this->request->post("product/a"));
                        if ($product_data){
                            foreach ($product_data as &$r) {
                                $r['business_id'] = $business_id;
                            }
                            $productModel->saveAll($product_data);
                        }

                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("product_list", $row->product);
        return $this->view->fetch();

    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 意向产品
     */
    public function product($business_id = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if (!$business_id) $this->error(__("商机ID有误"));

        $this->model = model("app\admin\model\\facrm\business\Product");

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where('business_id', $business_id)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($where)
            ->where('business_id', $business_id)
            ->with(['info'])
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);

        return json($result);


    }

}
